const vm = new Vue({
    el: '#main',
    data: {
        verified: false,
        sex: '男',
        date: '年/月/日',
        nation: '请选择',
        city: '请选择',
        job: '请输入',
        photo: '',
        idCard: '',
        trueName: '',
        nickName: '',
        reqData: {
            sex: '1',
            date: '',
            nation: '',
            city: '',
            job: '',
            intro: '',
        },
        tempDate: [0, 0, 0],
        bgImg: '../image/bg-img/1-151205143333.jpg',
        idVerify: fxj.getSearch().get('id_verify'),
    },
    methods: {},
});

function main() {
    fxj.fixLayout();
    getPersonalInformation();
    initNationPicker();
    initCityAreaPikcer();
    initSexPicker();
    initDatePicker();
}

function apiready() {
    main();
}

function initNationPicker() {
    const nationEl = document.getElementById('nation');
    const data = [
        {
            text: '汉族',
            value: 1,
        },
        {
            text: '壮族',
            value: 2,
        },
        {
            text: '满族',
            value: 3,
        },
        {
            text: '回族',
            value: 4,
        },
        {
            text: '苗族',
            value: 5,
        },
        {
            text: '维吾尔族',
            value: 6,
        },
        {
            text: '土家族',
            value: 7,
        },
        {
            text: '彝族',
            value: 8,
        },
        {
            text: '蒙古族',
            value: 9,
        },
        {
            text: '藏族',
            value: 10,
        },
        {
            text: '布依族',
            value: 11,
        },
        {
            text: '侗族',
            value: 12,
        },
        {
            text: '瑶族',
            value: 13,
        },
        {
            text: '朝鲜族',
            value: 14,
        },
        {
            text: '白族',
            value: 15,
        },
        {
            text: '哈尼族',
            value: 16,
        },
        {
            text: '哈萨克族',
            value: 17,
        },
        {
            text: '黎族',
            value: 18,
        },
        {
            text: '傣族',
            value: 19,
        },
        {
            text: '畲族',
            value: 20,
        },
        {
            text: '傈僳族',
            value: 21,
        },
        {
            text: '仡佬族',
            value: 22,
        },
        {
            text: '东乡族',
            value: 23,
        },
        {
            text: '高山族',
            value: 24,
        },
        {
            text: '拉祜族',
            value: 25,
        },
        {
            text: '水族',
            value: 26,
        },
        {
            text: '佤族',
            value: 27,
        },
        {
            text: '纳西族',
            value: 28,
        },
        {
            text: '羌族',
            value: 29,
        },
        {
            text: '土族',
            value: 30,
        },
        {
            text: '仫佬族',
            value: 31,
        },
        {
            text: '锡伯族',
            value: 32,
        },
        {
            text: '柯尔克孜族',
            value: 33,
        },
        {
            text: '达斡尔族',
            value: 34,
        },
        {
            text: '景颇族',
            value: 35,
        },
        {
            text: '毛南族',
            value: 36,
        },
        {
            text: '撒拉族',
            value: 37,
        },
        {
            text: '塔吉克族',
            value: 38,
        },
        {
            text: '阿昌族',
            value: 39,
        },
        {
            text: '普米族',
            value: 40,
        },
        {
            text: '鄂温克族',
            value: 41,
        },
        {
            text: '怒族',
            value: 42,
        },
        {
            text: '京族',
            value: 43,
        },
        {
            text: '基诺族',
            value: 44,
        },
        {
            text: '德昂族',
            value: 45,
        },
        {
            text: '保安族',
            value: 46,
        },
        {
            text: '俄罗斯族',
            value: 47,
        },
        {
            text: '裕固族',
            value: 48,
        },
        {
            text: '乌兹别克族',
            value: 49,
        },
        {
            text: '门巴族',
            value: 50,
        },
        {
            text: '鄂伦春族',
            value: 51,
        },
        {
            text: '独龙族',
            value: 52,
        },
        {
            text: '塔塔尔族',
            value: 53,
        },
        {
            text: '赫哲族',
            value: 54,
        },
        {
            text: '珞巴族',
            value: 55,
        },
        {
            text: '布朗族',
            value: 56,
        },
        {
            text: '其他',
            value: 57,
        },
    ];
    const picker = new Picker({
        data: [data],
        selectedIndex: [0],
        title: '选择民族',
    });

    picker.on('picker.valuechange', (selectedVal, selectedIndex) => {
        vm.reqData.nation = selectedVal[0];
        vm.nation = data[selectedIndex].text;
    });

    nationEl.addEventListener('click', () => {
        picker.show();
    });
}

function initCityAreaPikcer() {
    const cityArea = new City();
    const nationEl = document.getElementById('cityArea');

    const picker = new Picker({
        data: [cityArea.province, cityArea.city],
        selectedIndex: [0, 0],
        title: '选择地区',
    });

    picker.on('picker.change', (index, selectedIndex) => {
        if (index === 0) {
            picker.refillColumn(1, cityArea.getCityByProvince({index: selectedIndex}));
        }
    });

    picker.on('picker.valuechange', (selectedVal, selectedIndex) => {
        vm.reqData.city = selectedVal[1];
        vm.city = cityArea.city[selectedIndex[1]].text;
    });

    nationEl.addEventListener('click', () => {
        picker.show();
    });
}

function initSexPicker() {
    const nationEl = document.getElementById('sexPicker');
    const sex = [
        {
            text: '男',
            value: 1,
        },
        {
            text: '女',
            value: 0,
        },
    ];
    const picker = new Picker({
        data: [sex],
        selectedIndex: [0],
        title: '选择性别',
    });
    picker.on('picker.valuechange', (selectedVal, selectedIndex) => {
        vm.sex = sex[selectedIndex].text;
        vm.reqData.sex = selectedVal[0];
    });

    nationEl.addEventListener('click', () => {
        picker.show();
    });
}

function initDatePicker() {
    let DatePickerData = null;
    const nationEl = document.getElementById('datePicker');
    const date = new Date();
    const year = (() => {
        const dataYear = [];
        const nowYear = date.getFullYear();
        let oldYear = nowYear - 80;
        for (; oldYear <= nowYear; oldYear++) {
            dataYear.unshift({
                text: oldYear,
                value: oldYear,
            });
        }
        return dataYear;
    })();
    const month = (() => {
        const dataMonth = [];
        for (let i = 1; i <= 12; i++) {
            dataMonth.push({
                text: `${i}月`,
                value: i,
            });
        }
        return dataMonth;
    })();
    const day = getAllDay(date.getFullYear(), 1);
    DatePickerData = [year, month, day];
    const picker = new Picker({
        data: DatePickerData,
        selectedIndex: [0, 0, 0],
        title: '选择出生日期',
    });
    vm.tempDate[0] = year[0].value;
    vm.tempDate[1] = month[0].value;
    vm.tempDate[2] = day[0].value;

    picker.on('picker.change', (index, selectedIndex) => {
        vm.tempDate[index] = DatePickerData[index][selectedIndex].value;
        if (index === 0 || index === 1) {
            picker.refillColumn(2, getAllDay(vm.tempDate[0], vm.tempDate[1]));
        }
    });

    picker.on('picker.valuechange', (v) => {
        vm.date = `${v[0]}年${v[1]}月${v[2]}日`;
        vm.reqData.date = `${v[0]}-${v[1]}-${v[2]}`;
    });

    nationEl.addEventListener('click', () => {
        picker.show();
    });
}

function getAllDay(year, month) {
    switch (month) {
        case 1:
        case 3:
        case 5:
        case 7:
        case 8:
        case 10:
        case 12:
            return createDay(31);
        case 2:
            return createDay(year % 4 === 0 ? 29 : 28);
        case 4:
        case 6:
        case 9:
        case 11:
            return createDay(30);
    }
}

function createDay(num) {
    return new Array(num).fill(0).map((v, i) => {
        i++;
        return {
            text: `${i}日`,
            value: i,
        };
    });
}

async function getPersonalInformation() {
    const result = await ajax({
        url: 'home/userCenter/personalInformation',
        type: 'POST',
        data: {
            role: 2,
        },
    });
    if (result.err !== 0) {
        toast(result.msg);
        return;
    }
    const info = result.data;
    if (info.idcard) {
        vm.idCard = info.idcard;
        vm.trueName = info.truename;
        vm.verified = true;
    }
    vm.sex = info.sex === '1' ? '男' : '女';
    vm.nation = !!info.nation ? info.nation : '请选择';
    if (info.date_birth) {
        vm.date = info.date_birth.replace('-', '年').replace('-', '月') + '日';
    }
    vm.city = info.city ? info.city : '请选择';
    vm.reqData.job = info.occupation ? info.occupation : '';
    vm.reqData.intro = info.introduce ? info.introduce : '';
    vm.nickName = info.nickName;
    vm.photo = info.photo;
}

async function save() {
    const close = fxj.dialog.loading({noBg: true});
    const data = {
        sex: vm.reqData.sex,
        nickName: vm.nickName,
        nation: vm.reqData.nation,
        cityId: vm.reqData.city,
        occupation: vm.reqData.job,
        introduction: vm.reqData.intro,
        birth: vm.reqData.date,
    };
    const result = await ajax({
        url: 'home/userCenter/ModifyPersonalInformation',
        type: 'POST',
        data,
    });
    if (apiOk()) {
        api.execScript({
            name: 'root',
            frameName: 'me',
            script: 'update()',
        });
    }
    close();
    toast(result.msg);
    if (result.err === 0) {
        setTimeout(() => {
            fxj.closeWin();
        }, 1500);
    }
}

function uploadImg() {
    const ipt = document.getElementById('avatarFile');
    ipt.click();
    ipt.addEventListener('change', async e => {
        const files = e.target.files;
        const file = files.length > 0 ? files[0] : null;
        if (!file) return;
        const formData = new FormData();
        formData.append('imgFile', file);
        formData.append('token', localStorage.getItem('token'));
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = e => {
            vm.photo = e.target.result;
        };
        let res = await fetch(`http://fxj178.com/home/AppUploadImg/uploadHeadImg`, {
            method: 'POST',
            body: formData,
            mode: 'cors',
        });
        res = await res.json();
        if (res.err === 0) {
            toast('头像更新成功');
        }
        else {
            toast(res.msg);
        }
        getPersonalInformation();
    });
}
